package com.demo.base.web.webmvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 初始化需要在会话周期内共享的变量
 * Created by ethan on 2017/2/10.
 */
public class InitHttpContextInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(InitHttpContextInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.debug("初始化WebRequestContext");
        RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
        attributes.setAttribute(HttpContextConst.CURRENT_HTTP_REQUEST, httpServletRequest, RequestAttributes.SCOPE_REQUEST);
        attributes.setAttribute(HttpContextConst.CURRENT_HTTP_RESPONSE, httpServletResponse, RequestAttributes.SCOPE_REQUEST);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        RequestContextHolder.resetRequestAttributes();
    }

}
